package ComExWeb.util;

import ComExWeb.dominio.security.Usuario;
import java.security.Security;
import java.util.Properties;

import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import org.hibernate.tool.hbm2x.StringUtils;

/**
 *
 * @author Giliard
 */
public class EmailUtils  {

    String username = "bolaosucesso";
    String password = "giliardsimoes";

    public void enviaEmail(HttpServletRequest request, String destinatarios, String assunto,
            String corpo) throws Exception {

        String host = "smtp.gmail.com";
        try {

            Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
            
            Properties props = new Properties();
            props.setProperty("mail.transport.protocol", "smtp");
            props.setProperty("mail.host", host);
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.debug", "true");
            props.put("mail.smtp.port", "465");
            props.put("mail.smtp.socketFactory.port", "465");
            props.put("mail.smtp.socketFactory.class",
                    "javax.net.ssl.SSLSocketFactory");
            props.put("mail.smtp.socketFactory.fallback", "false");
            props.setProperty("mail.smtp.quitwait", "false");

            Session session;
            session = Session.getInstance(props,
                    new javax.mail.Authenticator() {

                @Override
                        protected PasswordAuthentication getPasswordAuthentication() {
                            return new PasswordAuthentication(username, password);
                        }
                    });

            MimeMessage message = new MimeMessage(session);
            message.setSender(new InternetAddress("bolaosucesso@gmail.com"));
            message.setSubject(assunto);
            message.setContent(corpo, "text/plain");
            message.setRecipients(Message.RecipientType.TO, destinatarios);

            Transport.send(message);

        } catch (AddressException e) {
            // throw new Exception("erro.envio.email", new Object[]{e.getMessage()});
        } catch (MessagingException m) {
            throw new Exception("erro.envio.email " + m);
        }
    }

    InternetAddress[] getMailIDs(String ids) throws AddressException {
        try {
            ids = StringUtils.replace(ids, ";", ",");
            return InternetAddress.parse(ids, true);
        } catch (AddressException e) {
            return null;
        }
    }

    public void enviaEmailConfirmacao(Usuario usuario) throws Exception {

        HttpServletRequest request = getRequest();

        String assunto = "Confirmação de cadastro no Bolão";
        EmailUtils email = new EmailUtils();
        try {
            email.enviaEmail(request, usuario.getEmail(), assunto, contruirCorpoEmail(usuario));
        } catch (Exception e) {
            throw new Exception("Não foi possível enviar e-mail - " + e.getMessage());
        }
    }

    public void enviaEmailMantenedor(String loginUsuario) throws Exception{
        HttpServletRequest request = getRequest();

        String assunto = "Novo usuário cadastrado no bolão";
        EmailUtils email = new EmailUtils();
        try {
            email.enviaEmail(request, "gilihamu@gmail.com", assunto,"Usuario "+loginUsuario+" fez o cadastro do bolão! Aguarde o pagamento");
        } catch (Exception e) {
            throw new Exception("Não foi possível enviar e-mail - " + e.getMessage());
        }
    }

    public String contruirCorpoEmail(Usuario usuario) {
        String corpoEmail = "";
        corpoEmail += "Clique no link para confirmar o seu cadastro do bolao ";
        corpoEmail += construirURLConfirmacao(usuario);
        return corpoEmail;
    }

    public String construirURLConfirmacao(Usuario usuario) {
        //String idCriptografado = CriptografiaSHA.criptografar(usuario.getId().toString());
        String idCriptografado = new StringUtil().md5(usuario.getId().toString());
        String loginUsuario = "?login=" + usuario.getLogin();
        String id = "&codigo=" + idCriptografado;
        String URL = "http://localhost:8080/grupocompramais/EmailServlet" + loginUsuario + id;
        return URL;
    }

    /**
     * Busca o objeto {@link HttpServletRequest}, para a requisição atual.
     */
    public HttpServletRequest getRequest() {
        ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
        return (HttpServletRequest) externalContext.getRequest();
    }
}
